<!--  -->
<template>
  <div class="invoice-issuer-add-item-con">
    <div class="iiai-row head">
      <div class="item"><h3><span class="icons"></span>{{pageTitle}}</h3> <a-tag v-if="pageConfig.isEdit" :color="stateList[userInfo.state].color" style="margin-left: 30px;"> {{stateList[userInfo.state].label}}</a-tag></div>
      <div class="item"> <a-button @click="goto">{{pageBackBtnLabel}}</a-button></div>
    </div>
    <div class="iiai-row form">
      <p-PageForm ref="addUserForm" :showHelp="false" v-bind="formConfig" :PEvent="PEvent"></p-PageForm>
      <div v-if="checkErrMsg && checkErrMsg" class="err">{{ checkErrMsg }}</div>
      <div class="btn-con"><a-button @click="addUser" :loading="btnloading" :disabled="isAddUserBtn"  type="primary">添加关联企业 </a-button></div>
    </div>
    <a-divider v-if="NotReported.show" orientation="left">已添加的企业</a-divider>
    <div v-if="pageConfig.isEdit" class="iiai-row query-group">
      <a-form-model :layout="'inline'" :model="form" v-bind="formItemLayout">
        <a-form-model-item label="企业名称">
          <a-input v-model="form.entName" placeholder="请输入企业名称" allowClear style="width: 100%;" @change="queryEvent" />
        </a-form-model-item>
        <a-form-model-item label="渠道名称">
          <a-input v-model="form.name" placeholder="请输入渠道名称" allowClear style="width: 100%;" @change="queryEvent" />
        </a-form-model-item>
        <a-form-model-item label="密码状态">
          <a-select v-model="form.state" style="width: 120px" allowClear @change="queryEvent">
            <a-select-option v-for="(key,index) in Object.keys(tagConfig1)" :key="'a-select-option-'+index" :value="key">{{tagConfig1[key].label}} </a-select-option>
            <!-- <a-select-option value="1">使用中 </a-select-option>
            <a-select-option value="2">已停用 </a-select-option> -->
          </a-select>
        </a-form-model-item>
        <a-form-model-item :wrapperCol="{span: 24 }">
          <a-button type="primary" @click="queryEvent" :loading="btnQueryloading">  查询 </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div v-if="NotReported.show" class="iiai-row">
      <a-table :columns="NotReported.columnsAll" :data-source="NotReported.tableData" bordered :scroll="{y:300}" >

        <span slot="password" slot-scope="text, record">
          <EditPassword v-model="record" :isEditPageData="isEditPageData"></EditPassword>
          <!-- <template v-if="!isEditPageData && record.status == '4'">{{ text }}</template>
          <template v-if="isEditPageData && record.status == '1'"><a-input v-model="record.password" placeholder="Basic usage" /></template> -->
        </span>
        <span slot="pwd" slot-scope="text, record">{{ text.val}} </span>
        <span slot="pwd1" slot-scope="text, record">
          <!-- action:{state:'0', isEdit:false, isDelete: false} -->
          <a-tag :color="tagConfig[text.state].color">{{tagConfig[text.state].label}}</a-tag>
        </span>
        <span slot="status" slot-scope="text, record">
          <!-- 0-未设置 1-使用中 2-密码错误 3-已删除 4-停用 -->
          <a-tag :color="tagConfig1[text].color">{{tagConfig1[text].label}}</a-tag>
        </span>
        <span slot="action" slot-scope="text, record">
          <!-- :disabled="!isEditPageData" -->
           <template v-if="iatDetail.bizType != '3' && isFreeze == false">
             <a-button v-if="pageConfig.isEdit && record.status == '1'" v-has="'qsb_imd_edit:view:table_btn1'" type="link" :disabled="isEditPageData" @click="DeactivateUser(record)"> 停用</a-button>
             <a-button v-if="pageConfig.isEdit && record.status == '4'" v-has="'qsb_imd_edit:view:table_btn2'" type="link" :disabled="isEditPageData" @click="EnableUser(record)"> 启用</a-button>
             <a-button v-if="pageConfig.isEdit && record.status == '2'" v-has="'qsb_ia_add:view:table_btn1'" type="link" @click="checkUser(record)" >校验密码</a-button>
             <a-button v-if="getDeleteWhere(record, pageConfig.isEdit)" v-has="'qsb_ia_add:view:table_btn2'" type="link" @click="removeUser(record)"> 删除</a-button>
           </template>
        </span>
      </a-table>
    </div>
    <div v-if="NotReported.show && iatDetail.bizType != '3' && isFreeze == false" class="iiai-row btn-group">
      <a-button v-has="'qsb_ia_add:edit:btn3'" v-if="!pageConfig.isEdit"  type="primary" @click="saveUser" style="margin: 0 5px;">保存开票员</a-button>
      <a-button v-has="'qsb_imd_edit:edit:btn3'" v-if="pageConfig.isEdit && !isAddUserBtn" type="primary" @click="saveAddQY" style="margin: 0 5px;">保存开票员关联企业</a-button>
      <a-button v-has="'qsb_imd_edit:edit:btn3'" v-if="pageConfig.isEdit && !isEditPageData" type="primary" @click="editUser" style="margin: 0 5px;">修改开票员</a-button>
      <a-button v-has="'qsb_imd_edit:edit:btn4'" v-if="pageConfig.isEdit && !isEditPageData" type="danger" @click="stopUser" style="margin: 0 5px;">停用开票员</a-button>
      <a-button v-has="'qsb_imd_edit:edit:btn5'" v-if="pageConfig.isEdit && isEditPageData && userInfo.state != '0'" type="primary" @click="saveEditUser" style="margin: 0 5px;">保存开票员信息</a-button>
      <a-button v-has="'qsb_imd_edit:view:btn6'" v-if="pageConfig.isEdit && isEditPageData && userInfo.state != '0'" @click="ExitEditing" style="margin: 0 5px;">退出开票员信息编辑</a-button>
      <a-button v-has="'qsb_imd_edit:edit:btn7'" v-if="userInfo.state == '0'" @click="EnableInvoicer" type="primary" style="margin: 0 5px;">启用开票员</a-button>
      <!-- <a-button v-if="pageConfig.isEdit && isEditPageData" type="primary" @click="checkUser" style="margin: 0 5px;">校验密码</a-button> -->
    </div>
    <OpenModal v-bind="OpenModalConfig" :closeEvent="OpenModalCloseEvent"></OpenModal>
  </div>
</template>

<script>
import getDataDB from '@/api/InvoiceIssuer.js'
import {queryLoginChannel} from '@/api/enterprise.js'
import formConfig from './utils/formConfig'
import OpenModal from './OpenModal.vue'
import tableConfig from './OpenModalComponent/utils/tableConfig'

const EditPassword = {
  props: {
    value: { type: Object },
    isEditPageData: { type: Boolean }
  },
  data() {
    return {
      dataUrl: ''
    }
  },
  watch: {
    url: {
      handler(val) {

      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getItem(dataList, isEP){
      if (dataList.status == '1' && isEP == true) {
        return (<a-input v-model={dataList.password} placeholder="请输入密码" />)
      }
      if (dataList.status == '0' && dataList.isNew == true) {
        return dataList.password
      }
      if (dataList.isNew == true) {
        return (<a-input v-model={dataList.password} placeholder="请输入密码" />)
      }


      return dataList.password
    }
  },
  render: function(h) {
    const { value, isEditPageData } = this
    return (<span>
      {this.getItem(value, isEditPageData)}
    </span>)
  }
}

export default {
  // import引入的组件需要注入到对象中才能使用
  name: 'InvoiceIssuerAddItem',
  components: {OpenModal, EditPassword},
  props: {
    pageConfig: {
      type: Object,
      default: ()=>{ return {
        isEdit:false
      }}
    }
  },
  data() {
    // 这里存放数据
    return {
      pageTitle: '新增开票员',
      pageBackBtnLabel:'放弃编辑',
      isFreeze: false, // 表示是否冻结所有操作 默认false 表示不冻结
      isAddUserBtn:false, // 添加关联企业
      isEditPageData: false, // 表示是否在详情中启用编辑数据的功能
      isEditTableDeletePageData: false, // 用于控制表格中的删除操作
      btnloading: false,
      btnQueryloading: false,
      formConfig:{ ...formConfig() },
      formVal:{},
      tagConfig:{ '0':{color:'',label:'待校验'},'1':{color:'#87d068',label:'校验成功'},'2':{color:'#f50',label:'校验失败'},'-1':{color:'orange',label:'校验中'}},
      // 0-未设置 1-使用中 2-密码错误 3-已删除 4-停用
      tagConfig1:{ '0':{color:'',label:'未设置'},'1':{color:'#87d068',label:'使用中'},'2':{color:'#f50',label:'密码错误'},'3':{color:'orange',label:'已删除'},'4':{color:'orange',label:'停用'}},
      NotReported: {
        show:false,
        tableData: [],
        tableData1: [],
        tempTableData:[],
        columnsAll: tableConfig('InvoiceIssuerAddItem-edit'),
      },
      OpenModalConfig: {
        visible: false,
        componentName:'',
        data:{}
      },
      ChannelInfoList:[],
      checkErrMsg:"",
      formItemLayout: { labelCol: { span: 10 }, wrapperCol: { span: 14 } },
      form:{
        entName:'',
        name:'',
        state:''
      },
      stateList: {
        '2': { color: '', label: '未启用' },
        '0': { color: 'orange', label: '已停用' },
        '1': { color: 'green', label: '使用中' },
      },
      userInfo:{
        state: 2
      },
      iatDetail:{},
      ChannelInfo: {}
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {
    pageConfig: {
      handler(val) {
       if (!this.isType.isNullOrUnDef(val) && !this.isType.isEmpty(val)) {
        const {isEdit} = val
        const temp = formConfig()
        if (isEdit=== true) {
          this.pageTitle = '开票员详情'
          this.pageBackBtnLabel = '返回'
          // 默认进入详情页面时 允许 添加关联企业  ，当点击修改开票员 之后禁用此按钮
          this.isAddUserBtn = false // 禁用 添加关联企业
          this.NotReported.show = true
          this.NotReported.columnsAll = tableConfig('InvoiceIssuerAddItem-edit')
          const tempArr = []

          temp.formDataList.forEach(item=>{
            const tempObj = {...item}
            tempObj.itemAttr['disabled'] = true
            tempArr.push({...tempObj})
          })
          this.formConfig.formDataList = tempArr
          // 需要从数据库中查询已有数据
        } else {
          this.pageTitle = '新增开票员'
          this.pageBackBtnLabel = '放弃编辑'
          this.isAddUserBtn = false // 起用 添加关联企业
          this.NotReported.show = false
          this.NotReported.columnsAll = tableConfig('InvoiceIssuerAddItem')
          const tempArr = []
          temp.formDataList.forEach(item=>{
            const tempObj = {...item}
            tempObj.itemAttr['disabled'] = false
            tempArr.push({...tempObj})
          })
          this.formConfig.formDataList = tempArr
        }
        this.getChannelInfo()
        console.log("@####################", isEdit, this.formConfig.formDataList, temp);
       }
      },
      deep: true,
      immediate: true
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    console.log(this.$route.query.id);
    this.init()
  },
  // 方法集合
  methods: {
    saveAddQY(){
      const tempArr = this.NotReported.tableData.filter(item=>item.status=='0').map(item=>{
        return {
          "entId": item.entId,
          "password": item.password,
          "parentId": this.iatDetail.id,
          // "id": item.id,
          "phone": this.iatDetail.phone,
          "showFlag": "1", // 管理端 0  企业端 1
          "source": "2",
          "type": 2
        }
      })
      if(tempArr.length==0){
        this.$message.warning('请添加关联企业后再操作！')
        return false
      }
      getDataDB('添加关联企业',tempArr).then(res => {
        // console.log('添加关联企业======>',res);
        if(res.success == true){
          this.$message.success('操作成功！')
          this.init()
        } else {
          this.$message.warning(res.message)
        }

      })
    },
    init() {
      this.queryLoginChannel_()
      this.getChannelInfo()
      this.getDataForDetail()
    },
    queryLoginChannel_() {
      queryLoginChannel().then(res => {
        if (res.success == true) {
          const { channelInfoVo } = res.result
          this.ChannelInfo = channelInfoVo
        }
      })
    },
    getDataForPageTable(bk) {
      if (this.pageConfig.isEdit == false) {
        return false
      }
      const userID = this.iatDetail.id
      // this.NotReported.tempTableData
      getDataDB('开票员详情关联的企业信息',{id:userID}).then(res => {
        let tempArr = [...res.result.map(item => {
          return {...item,"startTime|endTime": `${item.startTime}~${!this.isType.isNullOrUnDef(item.endTime) && item.endTime || ''}`,oldStatus:item.status, isNew: false, deketeKey: item.id } // , status: 4
        })]
        if(this.NotReported.tempTableData.length > 0) {
          tempArr = [ ...this.NotReported.tempTableData, ...res.result]
        }
        this.NotReported.tableData = tempArr
        this.NotReported.tableData1 = tempArr
        bk&&bk(tempArr)
      })
    },
    getDataForDetail() {
      const tempObj = {
        "name":"name",
        "idCard":"cardNum",
        "phone":"phone",
        "bizType":"dw"
      }
      const id = this.$route.query.id
      if (!id) {
        return false
      }
      getDataDB('开票员详情',{id}).then(res => {
        console.log('开票员详情========>',res);
        this.iatDetail = res.result
        this.formConfig.formDataList[0].value = res.result.name
        this.formConfig.formDataList[1].value = res.result.idCard
        this.formConfig.formDataList[2].value = res.result.phone
        // this.formConfig.formDataList[3].value = res.result.bizType + ''
        this.userInfo.state = res.result.status + '' || '2'
        this.isEditPageData = res.result.status == '0' ? true : false
        // 当前人员如果是内部员工或者企业法人时 不允许操作 20240813 10:04
        if(this.iatDetail.bizType == '2'){
          this.isFreeze = false
          this.isAddUserBtn = false
        } else {
          this.isFreeze = true
          this.isAddUserBtn = true
        }
        // if (res.result.bizType=='3') {
        //   // 经营者  当前页面所有操作均不能使用
        // }
        // this.$nextTick(()=>{
        //   console.log('res.result.channelId==============>', res.result.channelId);
        //   if (res.result.bizType == '2') {
        //     this.PEvent('change','dw',res.result.bizType + '', res.result.channelId)
        //   }
        // })
        // 0-未设置 1-使用中 2-密码错误 3-已删除 4-停用
        const tempArr = res.result.relevance.map(item => {
          return {...item,"startTime|endTime": `${item.startTime}~${ !this.isType.isNullOrUnDef(item.endTime) && item.endTime || ''}`,oldStatus:item.status, isNew: false, deketeKey: item.id } // , status: 4
        })
        this.NotReported.tableData = tempArr
        this.NotReported.tableData1 = tempArr
      })
    },
    getChannelInfo(){
      // getDataDB('有效渠道管理列表',{}).then(res => {
      //   if(res.success==true){
      //     const tempArr = res.result.map(item=>{
      //       return  { label: item.channelName, value: item.id }
      //     }) || []
      //     this.ChannelInfoList = tempArr
      //     if (this.formConfig.formDataList.length == 5) {
      //       this.formConfig.formDataList[4].optionList = tempArr
      //     }
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // })
    },
    PEvent(type,item,data, qdVal=''){
      // change dw 2
      // console.log('==============>',type,item,data, qdVal);
      if (type == 'change' && item == 'dw'){
        if(data == '2') {
          const temp = { disabled: false }
          if(this.pageConfig.isEdit == true){
            temp.disabled = true
          }
          temp.showSearch = true
          temp.filterOption = (input, option)=>{
            return ( option.componentOptions.children[0].text.indexOf(input) >= 0 )
          }
          const tempArr_ = this.formConfig.formDataList.filter(item => item.enName == 'qd')
          // console.log('****************@@@@@@@@@@@@***********************************', JSON.stringify(this.ChannelInfoList));
          if (tempArr_.length == 0) {
            this.formConfig.formDataList.push({ enName:'qd', cnName:'所属渠道', type:'select',value:qdVal, numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{ placeholder:'请选择所属渠道', ...temp },optionList:this.ChannelInfoList,isChangeEvent:false,})
          }
          this.formConfig.formDataList.forEach(item_ => {
            const {enName} = item_
            const tempVal = this.$refs['addUserForm'].form[enName]
            if(enName == item){
              item_.value = data
            } else {
              item_.value = tempVal
            }
            if (enName == 'qd') {
              item_.value = qdVal
            }
            // console.log(enName, item_.value , data, enName == item);
          })
        } else {
          const tempArr = []
          this.formConfig.formDataList.forEach(item => {
            if (item.enName != 'qd') {
              tempArr.push(item)
            }
          })
          this.formConfig.formDataList = tempArr
        }

      }

    },
    goto(){
      this.$router.go(-1)
    },

    async checkUserInfo(formData){
      const param = {
        bizType: '2',
        idCard:  formData.cardNum,
        name:  formData.name,
        phone:  formData.phone,
        type: '2'  // 身份（0-经营者 1-办税员 2-开票员 3-财务负责人
      }
      if (formData.dw == 2) {
        param['bizNo'] = formData.qd
      }
      if (this.pageConfig.isEdit == true) {
        param['id'] = this.iatDetail.id
      }
      this.checkErrMsg = ""
      const res = await getDataDB('供应商三要素及去重验证',param)
      if(res.success != true){
        this.checkErrMsg = res.message
        this.$message.warning(res.message)
      }
      return res.success
    },
    EditDataConfig(){
      const notEditArr = ['cardNum']
      const tempArr = []
      this.formConfig.formDataList.forEach(item=>{
        const tempObj = {...item}
        if (notEditArr.indexOf(item.enName) < 0 ) {
          tempObj.itemAttr['disabled'] = false
        }
        tempArr.push(tempObj)
      })
      this.formConfig.formDataList = tempArr
      this.isEditPageData = true
      // 禁用添加企业按钮
      // this.isAddUserBtn = false
      this.isAddUserBtn = true
    },
    // 修改开票员
    editUser(){
      // 默认进入详情页面时 允许 添加关联企业  ，当点击修改开票员 之后禁用此按钮
      this.isAddUserBtn = true
      this.EditDataConfig()
    },
    // 退出编辑开票员
    ExitEditing(){
      const notEditArr = ['cardNum']
      const tempArr = []
      this.formConfig.formDataList.forEach(item=>{
        const tempObj = {...item}
        if (notEditArr.indexOf(item.enName) < 0 ) {
          tempObj.itemAttr['disabled'] = true
        }
        tempArr.push(tempObj)
      })
      this.formConfig.formDataList = tempArr
      this.isEditPageData = false
      this.isAddUserBtn = false
      // this.getDataForPageTable()
    },
    /**
     * 保存开票员
     */
     saveUser(){
      const source_ = '1' // 管理端 2  企业端  1
      const param = {
        bizNo: this.ChannelInfo.id,
        bizType: '2',
        idCard: this.formVal.cardNum,
        name: this.formVal.name,
        phone: this.formVal.phone,
        list: this.NotReported.tableData.map(item=>{
          return { entId: item.entId, password: item.pwd.val, phone: this.formVal.phone, source: source_, type: '2'}
        }),
        source: source_,
        type:'2'
      }
      getDataDB('保存开票人',param).then(res =>{
        if(res.success == true){
          this.$message.success('保存成功')
          this.goto()
          // this.$router.push({
          //   path: '/qsbManageSettings/invoiceIssuerManageDetails',
          //   query: {
          //     id: record.id
          //   }
          // })
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 保存开票员信息
    saveEditUser() {
      const source = '1' // 管理端 2   企业端 1
      const type = '2'
      const list = this.NotReported.tableData.filter(item => item.status == '1' || item.status == '0').map(item=>{
        const temp = {
            "entId": item.entId,
            "parentId": this.iatDetail.id,
            "password": item.password,
            "phone": this.formVal.phone,
            source,
            type
          }
          if(item['id'] && item['id'] ){
            temp['id'] = item['id']
          }
          return temp
      })
      this.$refs['addUserForm'].onSubmit((formRes)=>{
        this.formVal = formRes
        const param  = {
          "bizNo": this.iatDetail.bizNo,
          "bizType": this.iatDetail.bizType,
          "id": this.iatDetail.id,
          "idCard": this.formVal.cardNum,
          list,
          "name": this.formVal.name,
          // "password": "xxx",
          "phone": this.formVal.phone,
          source,
          type
        }
        if (this.formVal.qd && this.formVal.qd) {
          param['bizNo'] = this.formVal.qd
        }
        // console.log("&&&&&&&&&&&&&&&&&&&&&&&&&&&", param);
        getDataDB('修改开票人',param).then(res => {
          if (res.success == true) {
            this.$message.success('操作成功')
            this.isEditPageData = false
            const tempArr = []
            this.formConfig.formDataList.forEach(item=>{
              const tempObj = {...item}
              tempObj.itemAttr['disabled'] = true
              tempArr.push(tempObj)
            })
            this.formConfig.formDataList = tempArr
            this.isAddUserBtn = true
            this.init()
            // this.getDataForDetail()
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    // 启用开票员
    EnableInvoicer() {
      // const tempTable = this.NotReported.tableData.filter(item=>{  return item.status == '1'  }).map(item => {
      //   return { entId: item.entId, password: item.password, id: item.id, parentId:'', phone: '', source: '2', type: '2' }
      // })
      const param = {
        // "bizNo": this.iatDetail.channelId,
        // "bizType": this.iatDetail.bizType,
        "id": this.iatDetail.id,
        // "idCard": this.iatDetail.idCard,
        // "list": tempTable,
        // "name": this.iatDetail.name,
        // "phone": this.iatDetail.phone,
        // "source": "2", // 管理端 2  企业端 1
        // "type": "2"
      }
      getDataDB('启用开票人',param).then(res => {
        console.log('启用开票人======================>',res, param);
        if (res.success == true) {
          this.$message.success('操作成功')
          this.init()
          // this.$router.go(0);
        } else {
          this.EditDataConfig()
          this.$message.warning(res.message)
        }
      })
    },
    // 停用开票员
    stopUser(){
      // this.OpenModalConfig.componentName = 'UserDeactivationAndReassignment'
      // this.OpenModalConfig.data = { detail: this.iatDetail, table: this.NotReported.tableData.filter(item=>{
      //   return item.status == '1'
      // }) }
      // this.OpenModalConfig.visible = true
      this.getDataForDBUDAR({current: 1, pageSize: 10}, (tableList)=>{
        const {total} = tableList
        if (total > 0) {
          this.OpenModalConfig.componentName = 'UserDeactivationAndReassignment'
          this.OpenModalConfig.data = { detail: this.iatDetail, table: tableList, event: this.getDataForDBUDAR }
          this.OpenModalConfig.visible = true
        }
      })
    },
    // 保存开票员
    addUser(){
      const self = this
      this.$refs['addUserForm'].onSubmit((formRes)=>{
        console.log('====>', formRes);
        this.btnloading = true
        this.formVal = formRes
        self.checkUserInfo(formRes).then(res=>{
          if(res == true){
            self.OpenModalConfig.componentName = 'InvoicerBoundEnterprise'
            self.OpenModalConfig.data = {...formRes, table:this.NotReported.tableData.map(item=>{
              return item.entId
            })} // 如果NotReported.tableData中有数据，需要带上相关数据的id
            self.OpenModalConfig.visible = true
          }
        }).finally(()=>{
          this.btnloading = false
        })
        // self.OpenModalConfig.componentName = 'InvoicerBoundEnterprise'
        // self.OpenModalConfig.data = {...formRes}
        // self.OpenModalConfig.visible = true
      })
    },
    queryEvent(){

      const getData = (dataList, key, val) => {
        return dataList.filter(item => {
          return item[key] && item[key].toString().indexOf(val) >= 0
        })
      }
      this.btnQueryloading = true
      const ll = []
      let tempArr = this.NotReported.tableData1
      if (!this.isType.isEmpty(this.form.entName)) {
        tempArr = getData(tempArr, 'entName', this.form.entName)
      } else {
        ll.push(true)
      }
      if (!this.isType.isEmpty(this.form.name)) {
        tempArr = getData(tempArr, 'channelName', this.form.name)
      } else {
        ll.push(true)
      }
      if (!this.isType.isNullOrUnDef(this.form.state) && !this.isType.isEmpty(this.form.state)) {
        tempArr = getData(tempArr, 'status', this.form.state)
      } else {
        ll.push(true)
      }
      this.NotReported.tableData = tempArr

      this.btnQueryloading = false
    },
    // 获取启用列表删除的条件
    getDeleteWhere(rowData, isEdit){
      const {isNew} = rowData
      let res = true
      // 编辑状态
      if(isEdit == true) {
        if(isNew == false){
          // 详情带出的数据 不允许删除  新关联的 也不能删除
          // this.isEditTableDeletePageData = true
          res = false
        }
      }
      // 新增状态
      if(isEdit == false) {
        // this.isEditTableDeletePageData = false
        res = true
      }
      return res
    },
    /**
     * 列表删除
     * @param {*} rowData
     */
    removeUser(rowData){
      console.log('=====>',rowData);
      const tempArr = []
      this.NotReported.tableData.forEach(item=>{
        if (item.deketeKey !== rowData.deketeKey) {
          tempArr.push(item)
        }
      })
      this.NotReported.tableData = tempArr
      this.NotReported.tableData1 = tempArr
    },
    /**
     * 列表 停用
     * @param {*} rowData
     */
    DeactivateUser(rowData) {
      const self = this
      if (rowData.isNew == true) {
        this.$message.warning('新启用数据不允许此操作！')
        return false
      }
      this.$confirm({
        title: '停用提示',
        content: '确定要停用当前数据？',
        okText:'确定',
        cancelText: '取消',
        onOk() {
          return new Promise((resolve, reject) => {
            // setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
            getDataDB('关联企业停用',{ id: rowData.id }).then(res => {
              if (res.success == true) {
                rowData.status = 4
                rowData.oldStatus = 4
              } else {
                self.$message.warning(res.message)
              }
              resolve()
            })
          }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {},
      });

    },
     // 校验密码
     checkUser(rowData) {
      console.log("校验密码  ", rowData);
      this.checkUserPWD(rowData)
     },

     checkUserPWD(rowData){
        const tempObj = { ...rowData, status: 1, id: '',isNew: false, deketeKey: new Date().getTime() }
        const tempentId = rowData.entId
        let ishas = this.getDatas(tempentId)
        if (!ishas) {
          const param = {
            entId: rowData.entId,
            password: rowData.password,
            phone: this.$refs['addUserForm'].form['phone'],
            parentId: this.iatDetail.id,
            source: "2",
            type: '2'
          }
          getDataDB('关联企业启用',param).then(res=>{
            if (res.success == true) {
              // 需要刷新列表数据 调用接口
              this.getDataForPageTable()
              // this.NotReported.tableData.push(tempObj)
              // if (res.result.verify == true) {
              //   this.NotReported.tableData.push(tempObj)
              // } else {
              //   this.$message.warning(res.result.message)
              // }
            } else {
              this.$message.warning(res.message)
              // 密码错误
              if (res.code == -2101030245) {
                this.NotReported.tableData.push({...tempObj, status: 2, isNew: true })
              }
            }
          })
        } else {
          this.$message.warning('所选的当前企业已有启用的，请处理后再试!')
        }
     },
     getDatas(entId){
      const tempentId = entId // rowData.entId
        let ishas = false
        this.NotReported.tableData.forEach(item => {
          // 0-未设置 1-使用中 2-密码错误 3-已删除 4-停用
          if (item.entId == tempentId && (item.status == '1' || item.status == '2')) {
            ishas = true
          }
        })
        return ishas
     },
    /**
     * 列表 启用
     * @param {*} rowData
     */
    EnableUser(rowData) {
      const tempentId = rowData.entId
      if(rowData.oldStatus == rowData.status){
        this.checkUserPWD(rowData)
      } else {
        if (rowData.oldStatus == '1') {
          let ishas = this.getDatas(tempentId)
          if (!ishas) {
            rowData.status = 1
          } else {
            this.$message.warning('所选的当前企业已有启用的，请处理后再试!')
          }
        }
      }
    },
    OpenModalCloseEvent(v,data) {
      this.OpenModalConfig.visible = v
      console.log('后续事件处理 0=======>', v,data);
      if(!this.isType.isNullOrUnDef(data) && !this.isType.isEmpty(data)){
        this.$nextTick().then(()=>{
          this.omAction(data)
        })
      }
    },
    getDataForDBUDAR(pagination, bk){
       const tempTable = this.NotReported.tableData.filter(item=>{  return item.status == '1'  }).map(item => item.entId)
      const param = {
        "data": {
          "notBandFlag": 2, // 查询企业未绑定开票员的表示, 1 管理端 , 2 企业端
          id:this.iatDetail.id
        },
        "pageNo": pagination.current,
        "pageSize": pagination.pageSize
      }
      if (tempTable.length > 0) {
        param.data['entIds'] = tempTable
      }
      getDataDB('查询未绑定开票员的企业,查询未绑定内部员工或者渠道',param).then(res => {
        // console.log('**********************', res);
        if (res.success== true) {
          // const {records, total, current, size  } = res.result
          bk&&bk(res.result)
        }else {
          this.$message.warning(res.message)
        }
      })
    },
    omAction(data_){
      // console.log('后续事件处理=======>', data_);
      const {type,data} = data_
      const action = {
        'addUser': () => {
          // 填写统一密码
          this.OpenModalConfig.componentName = 'FillUnifiedPassword'
          this.OpenModalConfig.data = {...this.formVal, table:data }
          this.OpenModalConfig.visible = true
        },
        'goback': () => {
          // 返回 开票员绑定企业
          this.OpenModalConfig.componentName = 'InvoicerBoundEnterprise'
          this.OpenModalConfig.data = {...this.formVal, table:this.NotReported.tableData}
          this.OpenModalConfig.visible = true
        },
        'qj':()=>{
          // 密码校验成功 后返回的数据
          console.log(' 密码校验成功 后返回的数据====>',data_);
          const tempTable = data.table.map(item=>{
            const {action, ...args} = item
            const resI = {...args, deketeKey: item.entId}
            if(this.pageConfig.isEdit == true) {
              resI['password'] = item['pwd'].val
              resI['status'] = 0
              resI['startTime'] = ''
              resI['endTime'] = ''
              resI['isNew'] = true
            } else {
              resI['action'] = action
            }
            return resI
          })
          this.NotReported.tempTableData = tempTable
          console.log("密码校验成功 后返回的数据 1====>", tempTable);
          if(this.pageConfig.isEdit == true) {
            const tempArr = [...tempTable, ...this.NotReported.tableData]
            this.NotReported.tableData = tempArr
            this.NotReported.tableData1 = tempArr
          } else {
            this.NotReported.tableData = tempTable
            this.NotReported.tableData1 = tempTable
          }
          this.NotReported.show = true
        },
        'addPassword': () => {
          // 添加完成密码
        },
        // 停用及重新分配用户 的下一步
        'udar-next':() =>{
          this.OpenModalConfig.componentName = 'ReassignPersonnel'
          this.OpenModalConfig.data = { detail: this.iatDetail, table:data }
          this.OpenModalConfig.visible = true
        },
        // 停用及重新分配用户 的暂不配置
        'udar-close': () => {
          this.init()
        },
        // 重新绑定人员 下一步
        'rp-next': () =>{
          this.OpenModalConfig.componentName = 'PasswordVerifiers'
          this.OpenModalConfig.data = {...data, oldKPY: this.iatDetail}
          this.OpenModalConfig.visible = true
        },
        // 重新绑定人员 返回上一步
        'rp-goback': () => {
          // this.OpenModalConfig.componentName = 'UserDeactivationAndReassignment'
          // this.OpenModalConfig.data = { detail: this.iatDetail, table: this.NotReported.tableData }
          // this.OpenModalConfig.visible = true
          this.getDataForDBUDAR({current: 1, pageSize: 10}, (tableList)=>{
            const {total} = tableList
            if (total > 0) {
              this.OpenModalConfig.componentName = 'UserDeactivationAndReassignment'
              this.OpenModalConfig.data = { detail: this.iatDetail, table: tableList, event: this.getDataForDBUDAR }
              this.OpenModalConfig.visible = true
            }
          })
        },
        'pv-goback': () => {
          this.OpenModalConfig.componentName = 'ReassignPersonnel'
          this.OpenModalConfig.data = { ...data, detail: this.iatDetail }
          this.OpenModalConfig.visible = true
        },
        'pv-next': ()=>{
          this.getDataForDBUDAR({current: 1, pageSize: 10}, (tableList)=>{
            const {total} = tableList
            // const tempTable = tableList.filter(item=>{
            //   return item.status == '1'
            // })
            if (total > 0) {
              this.OpenModalConfig.componentName = 'UserDeactivationAndReassignment'
              this.OpenModalConfig.data = { detail: this.iatDetail, table: tableList, event: this.getDataForDBUDAR }
              this.OpenModalConfig.visible = true
            }
          })

        }
      }
      action[type] && action[type]()
    },

  },
  }
</script>
<style lang='less'>
.invoice-issuer-add-item-con{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-direction: column;
  .iiai-row{
    width: 100%;
    &.head{
      height: 50px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #d9d9d9;
      box-shadow: 0 2px 0 rgba(0, 0, 0, .015);
      .item{
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
    &.form{
      padding: 20px 0;
      .btn-con{
        padding: 0 200px;
      }
      .err{
        padding: 0 80px;
        color: red;
      }
    }
    &.btn-group{
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 10px 0;
    }
    &.query-group{
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 10px 0;
    }
  }
}
</style>
